package com.cn.server.module.chat.handler;

import com.cn.common.core.exception.ErrorResponse;
import com.cn.common.core.serial.Serializer;
import com.cn.server.Constant;
import com.cn.server.module.chat.service.ChatServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.cn.common.core.exception.ErrorCodeException;
import com.cn.common.core.model.Result;
import com.cn.common.core.model.ResultCode;
import com.cn.common.module.chat.request.PrivateChatRequest;
import com.cn.common.module.chat.request.PublicChatRequest;
import com.cn.server.module.chat.service.ChatService;

@Component
public class ChatHandlerImpl implements ChatHandler {

    private ChatService chatService = new ChatServiceImpl();

    @Override
    public <T extends Serializer> Result publicChat(String loginName, byte[] data) {
        try {
            //反序列化
            PublicChatRequest request = new PublicChatRequest();
            request.readFromBytes(data);

            //参数校验
            if (StringUtils.isEmpty(request.getContext())) {
                return Result.ERROR(ResultCode.AGRUMENT_ERROR, Constant.AGRUMENT_ERROR);
            }

            //执行业务
            chatService.publicChat(loginName, request.getContext(), request.getTypeu());
            return Result.SUCCESS(new ErrorResponse(ResultCode.SUCCESS, Constant.SUCCESS));
        } catch (ErrorCodeException e) {
            return Result.ERROR(new ErrorResponse(e.getErrorCode(), e.getErrorReason()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(new ErrorResponse(ResultCode.UNKOWN_EXCEPTION, Constant.SYSTEM_ERROR));
        }
    }

    @Override
    public <T extends Serializer> Result privateChat(String loginName, byte[] data) {
        try {
            //反序列化
            PrivateChatRequest request = new PrivateChatRequest();
            request.readFromBytes(data);

            //参数校验
            if (StringUtils.isEmpty(request.getContext()) || StringUtils.isEmpty(request.getTargetLoginName())) {
                return Result.ERROR(ResultCode.AGRUMENT_ERROR, Constant.AGRUMENT_ERROR);
            }

            //执行业务
            chatService.privateChat(loginName, request.getTargetLoginName(), request.getContext(), request.getTypeu());
            return Result.SUCCESS(new ErrorResponse(ResultCode.SUCCESS, Constant.SUCCESS));
        } catch (ErrorCodeException e) {
            return Result.ERROR(new ErrorResponse(e.getErrorCode(), e.getErrorReason()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(new ErrorResponse(ResultCode.UNKOWN_EXCEPTION, Constant.SYSTEM_ERROR));
        }
    }
}
